package handler

import (
	"cargo-admin/cache"
	"cargo-admin/model"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func UserList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))
	offset := (page - 1) * size
	var user []model.User
	redis_key := "user_list" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Offset(offset).Limit(size).Find(&user).Debug()
		JsonData, _ := json.Marshal(user)
		cache.Rdb.Set(cache.Ctx, redis_key, JsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &user)
	}
	var total int64
	model.DB.Model(&model.User{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "OK",
		"data":  user,
		"total": total,
	})
	return
}
func UserDetail(c *gin.Context) {
	id := c.Query("id")
	var user model.User
	redis_key := "user_detail" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Where("id=?", id).Find(&user).Debug()
		JsonData, _ := json.Marshal(user)
		cache.Rdb.Set(cache.Ctx, redis_key, JsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &user)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "OK",
		"data": user,
	})
	return
}
